<?php

/*
 * Controller/EmailController.php
 */

namespace RHX\Controller;

use RHX\Model\Object\Email;
use RHX\Model\Table\EmailTable;

class EmailController extends RHXController {

    /**
     * Page d'accueil
     *
     * @return array
     */
    public function indexAction() {
	return array();
    }

    /**
     * Chargement du contenu de la page d'accueil
     *
     * @return array
     */
    public function loadIndexAction() {
	// Changement de layout
	$this->layout('layout/ajax');

	// table
	$emailTable = new EmailTable($this->getAdapter());

	// POST
	$post = $this->getRequest()
		->getPost();

	// Tous les emails
	$emailList = $emailTable->getAll();

	return array(
	    'emails' => $emailList,
	);
    }

    /**
     * Ajouter un nouveau
     *
     * @return array
     */
    public function addNewAction() {
	// Changement de layout
	$this->layout('layout/ajax');

	// table
	$emailTable = new EmailTable($this->getAdapter());

	// POST
	$post = $this->getRequest()
		->getPost();

	// Nouveau Email
	$email = new Email($this->getAdapter(), $post);

	// Persistance dans la base de données
	$id		 = $emailTable->save($email);
	$email->id	 = $id;

	return array(
	    'email' => $email,
	);
    }

    /**
     * Editer
     *
     * @return array
     */
    public function editAction() {
	// Changement de layout
	$this->layout('layout/ajax');

	// POST
	$post = $this->getRequest()
		->getPost();

	// Table
	$emailTable = new EmailTable($this->getAdapter());

	// Requête SQL
	$pk	 = $post->pk;
	$name	 = $post->name;
	$value	 = addslashes($post->value);
	$sql	 = "UPDATE rh_email SET $name = '$value' WHERE id = $pk";

	$result = $emailTable->executeQuery($sql);

	return array(
	    'sql'	 => $sql,
	    'result' => $result,
	);
    }

    /**
     * Effacer un email
     * 
     * @return array
     */
    /*public function eraseAction() {
	// Changement de layout
	$this->layout('layout/ajax');

	// POST
	$post = $this->getRequest()
		->getPost();

	// Table
	$emailTable = new EmailTable($this->getAdapter());

	$nb = $emailTable->erase($post->id);

	return array(
	    'nb' => $nb
	);
    }*/
    
     public function eraseAction() {
	$id = (int) $this->params()->fromRoute('id', 0);
	$table	 = new EmailTable($this->getAdapter());
	$table->erase($id);

	return $this->redirect()->toRoute('RHX/default', array('controller' => 'email'));
    }

}

?>
